package com.ucode.hrm.controller;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.ucode.admin.ssm.auth.service.ApiAdminAuthService;
import com.ucode.enums.SysBaseEngineResultCodeEnum;
import com.ucode.enums.SysTypeEnum;
import com.ucode.hrm.service.HrmCustomerCompanyService;
import com.ucode.model.hrm.HrmCustomerCompany;
import com.ucode.model.hrm.convert.HrmCustomerCompanyConvert;
import com.ucode.model.hrm.enums.HrmSysResultCodeEnum;
import com.ucode.model.hrm.form.HrmCustomerCompanyForm;
import com.ucode.model.hrm.vo.HrmCustomerCompanyVO;
import com.ucode.model.sys.permission.Role;
import com.ucode.model.sys.permission.enums.RoleCodeEnum;
import com.ucode.model.sys.user.AdminUser;
import com.ucode.model.sys.user.SysOperator;
import com.ucode.ssm.permission.service.RoleService;
import com.ucode.ssm.user.service.AdminUserService;
import com.ucode.ssm.user.service.SysOperatorService;
import com.ucode.tool.base.Paginator;
import com.ucode.tool.base.ResponseResult;
import com.ucode.tool.base.enums.CommonSwitchStatusEnum;
import com.ucode.tool.exception.UcodeServiceException;
import com.ucode.tool.util.IdentifyUtils;
import com.ucode.tool.validator.InEnum;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Tag(name = "管理后台 - 人力资源系统 - 客户公司")
@RestController
@RequestMapping("/hrm/customer-company")
@Validated
public class HrmCustomerCompanyController {

    @Resource
    private HrmCustomerCompanyService customerCompanyService;
    @Resource
    private SysOperatorService sysOperatorService;
    @Resource
    private AdminUserService adminUserService;
    @Resource
    private RoleService roleService;
    @Resource
    private ApiAdminAuthService apiAdminAuthService;

    @GetMapping("/page-list")
    @Operation(summary = "获得分页列表")
    @PreAuthorize("@usfs.hasPermission('hrm:customer-company:query')")
    public ResponseResult<Paginator<HrmCustomerCompanyVO>> pageList(
            @Schema(description = "名称") @RequestParam(value = "companyName",required = false) String companyName,
            @Schema(description = "客户级别") @RequestParam(value = "level",required = false) Integer level,
            @Schema(description = "合作状态") @RequestParam(value = "status",required = false) Integer status,
            @Schema(description = "创建时间区间",example = "[2022-07-01 00:00:00,2022-07-01 23:59:59]")  @RequestParam(value = "createTimeInterval",required = false) LocalDateTime[] createTimeInterval,
            @Schema(description = "页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @Schema(description = "每页记录数",example="5") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize){

        Map<String,Object> condition = new HashMap<>();
        if(StrUtil.isNotBlank(companyName))
            condition.put("companyName", StrUtil.concat(true,"%", companyName,"%"));
        if(ArrayUtil.isNotEmpty(createTimeInterval) && createTimeInterval.length == 2){
            condition.put("startTime",createTimeInterval[0]);
            condition.put("endTime",createTimeInterval[1]);
        }
        condition.put("level",level);
        condition.put("status",status);
        condition.put("deltag",false);

        Paginator<HrmCustomerCompany> paginator = customerCompanyService.queryPageForList(condition,pageSize,pageNum);
        Paginator<HrmCustomerCompanyVO> paginatorVO =  HrmCustomerCompanyConvert.INSTANCE.convertPage(paginator);

        return ResponseResult.success(paginatorVO);
    }

    @GetMapping("/list-simple-page")
    @Operation(summary = "分页获取精简信息列表(没有权限校验，公共查询接口)", description = "主要用于前端的下拉选项")
    public ResponseResult<Paginator<HrmCustomerCompany>> simplePageList(@Schema(description = "关键字")  @RequestParam(value = "keyword",required = false) String keyword,
                                                                      @Schema(description = "页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                                      @Schema(description = "每页记录数",example="5") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
        Map<String,Object> condition = new HashMap<>();
        if(StrUtil.isNotBlank(keyword))
            condition.put("companyName", StrUtil.concat(true,"%", keyword,"%"));
        condition.put("deltag",false);

        Paginator<HrmCustomerCompany> paginator = customerCompanyService.queryPageForList(condition,pageSize,pageNum);
        return ResponseResult.success(paginator);
    }

    @GetMapping("/getById/{id}")
    @Parameter(description="主键ID",name = "id", required = true,in = ParameterIn.PATH,example = "1024")
    @Operation(summary = "主键获得信息")
    @PreAuthorize("@usfs.hasPermission('hrm:customer-company:query')")
    public ResponseResult<HrmCustomerCompanyVO> getById(@PathVariable(name="id",required=true) Long id){
        HrmCustomerCompany bean = customerCompanyService.validate(id);
        HrmCustomerCompanyVO vo = HrmCustomerCompanyConvert.INSTANCE.convert(bean);
        return ResponseResult.success(vo);
    }

    @PostMapping("/create")
    @Operation(summary = "创建")
    @PreAuthorize("@usfs.hasPermission('hrm:customer-company:create')")
    public ResponseResult<Long> create(@Valid @RequestBody HrmCustomerCompanyForm form) {
        HrmCustomerCompany bean = HrmCustomerCompanyConvert.INSTANCE.convert(form);
        bean.setId(IdentifyUtils.getDefaultSnowflakeId());

        if(ObjUtil.isNotNull(adminUserService.getUserByUsername(form.getCustomerAccount()))){
            //用户名重复
            throw new UcodeServiceException(HrmSysResultCodeEnum.CUSTOMER_USERNAME_EXISTS,form.getCustomerAccount());
        }

        Role role = roleService.selectByCode(RoleCodeEnum.OPS_ADMIN.getCode());
        if(ObjUtil.isNull(role)){
            throw new UcodeServiceException(SysBaseEngineResultCodeEnum.ROLE_OPERATOR_ADMIN_UNINITIALIZED);
        }

        Long id = customerCompanyService.insert(bean);

        //创建运营商
        SysOperator sysOperator = new SysOperator();
        sysOperator.setId(bean.getId());
        sysOperator.setName(bean.getCompanyName());
        sysOperator.setContact(bean.getContact());
        sysOperator.setMobile(bean.getMobile());
        sysOperator.setProvinceId(bean.getProvince());
        sysOperator.setCityId(bean.getCity());
        sysOperator.setAreaId(bean.getArea());
        sysOperator.setAddress(bean.getAddress());
        sysOperatorService.insert(sysOperator);

        //创建运营商账户
        if(ObjUtil.isNotNull(id)) {
            AdminUser adminUser = new AdminUser();
            adminUser.setUsername(bean.getCustomerAccount());
            adminUser.setNickname(bean.getCompanyName());
            adminUser.setSysType(SysTypeEnum.OPERATOR_SYS.getType());
            adminUser.setOperatorId(id);
            //初始密码
            adminUser.setPassword(apiAdminAuthService.encodedPassword("ucode@123456"));
            adminUserService.insert(adminUser, role.getId());
        }

        return id != null ? ResponseResult.success(id) : ResponseResult.failed();
    }

    @PostMapping("/update/{id}")
    @Parameter(description="主键ID",name = "id", required = true,in = ParameterIn.PATH,example = "1024")
    @Operation(summary = "修改")
    @PreAuthorize("@usfs.hasPermission('hrm:customer-company:update')")
    public ResponseResult<Object> update(@PathVariable(name="id",required=true) Long id,
                                         @Valid @RequestBody HrmCustomerCompanyForm form) {

        HrmCustomerCompany bean = HrmCustomerCompanyConvert.INSTANCE.convert(form);
        bean.setId(id);

        HrmCustomerCompany db_bean = customerCompanyService.validate( id);
        if(StrUtil.isNotBlank(db_bean.getCustomerAccount())) {
            bean.setCustomerAccount(null);//不允许修改
        }

        Role role = null;
        if(ObjUtil.isNull(db_bean.getCustomerAccount())){
            if(ObjUtil.isNotNull(adminUserService.getUserByUsername(form.getCustomerAccount()))){
                //用户名重复
                throw new UcodeServiceException(HrmSysResultCodeEnum.CUSTOMER_USERNAME_EXISTS,form.getCustomerAccount());
            }
            role = roleService.selectByCode(RoleCodeEnum.OPS_ADMIN.getCode());
            if(ObjUtil.isNull(role)){
                throw new UcodeServiceException(SysBaseEngineResultCodeEnum.ROLE_OPERATOR_ADMIN_UNINITIALIZED);
            }
        }

        int i = customerCompanyService.update(bean);
        if(i == 0)
            return ResponseResult.failed();


        if(ObjUtil.isNull(db_bean.getCustomerAccount())) {
            //创建运营商
            SysOperator sysOperator = new SysOperator();
            sysOperator.setId(bean.getId());
            sysOperator.setName(bean.getCompanyName());
            sysOperator.setContact(bean.getContact());
            sysOperator.setMobile(bean.getMobile());
            sysOperator.setProvinceId(bean.getProvince());
            sysOperator.setCityId(bean.getCity());
            sysOperator.setAreaId(bean.getArea());
            sysOperator.setAddress(bean.getAddress());
            sysOperatorService.insert(sysOperator);

            //创建运营商账户
            if(ObjUtil.isNotNull(id)) {
                AdminUser adminUser = new AdminUser();
                adminUser.setUsername(bean.getCustomerAccount());
                adminUser.setNickname(bean.getCompanyName());
                adminUser.setSysType(SysTypeEnum.OPERATOR_SYS.getType());
                adminUser.setOperatorId(id);
                //初始密码
                adminUser.setPassword(apiAdminAuthService.encodedPassword("ucode@123456"));
                adminUserService.insert(adminUser, role.getId());
            }
        }else {
            //更新运营商
            SysOperator sysOperator = new SysOperator();
            sysOperator.setId(bean.getId());
            sysOperator.setName(bean.getCompanyName());
            sysOperator.setContact(bean.getContact());
            sysOperator.setMobile(bean.getMobile());
            sysOperator.setProvinceId(bean.getProvince());
            sysOperator.setCityId(bean.getCity());
            sysOperator.setAreaId(bean.getArea());
            sysOperator.setAddress(bean.getAddress());
            sysOperatorService.update(sysOperator);
        }

        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }

    @PostMapping("/update-status")
    @Operation(summary = "修改状态")
    @PreAuthorize("@usfs.hasPermission('hrm:customer-company:update')")
    public ResponseResult<Boolean> updateStatus(@Schema(description = "编号集合",requiredMode = Schema.RequiredMode.REQUIRED)
                                                @NotEmpty(message = "编号集合为空")@Size(min = 1,max = 20,message = "编号集合数量为1-20条")
                                                @RequestParam(value = "ids",required = true) List<Long> ids,
                                                @Schema(description = "状态",requiredMode = Schema.RequiredMode.REQUIRED,allowableValues = {"0","1"})
                                                @InEnum(value = CommonSwitchStatusEnum.class, message = "修改的状态值必须是 {value}")
                                                @RequestParam(value = "status",required = true) Integer status) {
        int i = customerCompanyService.updateStatus(ids, status);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }


    @PostMapping("/logic-delete/{id}")
    @Operation(summary = "转移到回收站")
    @Parameter(description="主键ID",name = "id", required = true,in = ParameterIn.PATH, example = "1024")
    @PreAuthorize("@usfs.hasPermission('hrm:customer-company:logic-delete')")
    public ResponseResult<Object> logicDelete(@PathVariable(name="id",required=true) Long id) {
        //逻辑删除
        int i = customerCompanyService.logicDeletePrimaryKey(id);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }

    @PostMapping("/batch-logic-delete")
    @Operation(summary = "批量转移到回收站")
    @PreAuthorize("@usfs.hasPermission('hrm:customer-company:logic-delete')")
    public ResponseResult<Boolean> batchLogicDeletePrimaryKey(@Schema(description = "编号集合",requiredMode = Schema.RequiredMode.REQUIRED)
                                                @NotEmpty(message = "编号集合为空")@Size(min = 1,max = 100,message = "编号集合数量为1-100条")
                                                @RequestParam(value = "ids",required = true) List<Long> ids) {
        int i = customerCompanyService.logicDeleteByPrimaryKeys(ids);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }

}
